import React from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { Card, Table, Space, Button, Input, Drawer, Tabs, Form, Modal, message } from 'antd';
import { SyncOutlined, PlusOutlined } from '@ant-design/icons';
import { connect } from 'umi';
import moment from 'moment';
import request from '@/utils/request';
import { ColumnsType } from 'antd/es/table';
import { VendorSelect, WhseSelect, CustSelect } from '@/components/FormItemSelect';
import CateSelect from '@/components/CategoryComponent';
import Invoice from './Invoice'

const { TabPane } = Tabs;
const { Search } = Input;
const apiURL = '/api/services/app/PartTran/';
class ViewPage extends React.Component<any, any> {
    constructor(props: any) {
        super(props);
        this.state = {
            loading: false,
            dataSource: [],
            visible: false,
            selectedRowKeys: [],
            selectedRows: [],
            pageIndex: 1,
            pageSize: 10,
            totalCount: 0,
            payload: {},
            record: {},
            keywords: '',
        }
    }
    componentDidMount() {
        this.fetchDatas();
    }
    formRef: any = React.createRef();
    fetchDatas = (datas?: any) => {
        this.setState({ loading: true });
        const { pageIndex, pageSize, tranType } = this.state;
        if (datas) {
            datas.tranType = tranType;
            datas.checkOut = tranType ? 0 : -1;
        }
        request(apiURL + 'GetList', {
            method: 'GET',
            params: {
                SkipCount: (pageIndex - 1) * pageSize,
                MaxResultCount: pageSize,
                ...datas,
                desc: true
            },
        }).then((resp) => {
            if (resp && resp.result) {
                var dataSource = resp.result.items;
                var sumQty = resp.result.sumQty;
                var sumCost = resp.result.sumCost;
                this.setState({ loading: false, dataSource, totalCount: resp.result.totalCount, sumQty, sumCost });
            }
        });
    }
    onSelectChange = (selectedRowKeys: any, selectedRows: any) => {
        this.setState({ selectedRowKeys, selectedRows });
    };
    onSearch = (keywords: any) => {
        this.fetchDatas({ keywords });
    }
    swithDrawer = (visible: boolean, record = null) => {
        this.setState({ visible, record });
    }
    swithModel = (visible2: boolean) => {
        const { selectedRows } = this.state;
        if (selectedRows.length <= 0) {
            message.warning("请选择记录！")
            return;
        }
        this.setState({ visible2 });
    }
    tabChange = (key: any) => {
        let tranType = key === 'ALL' ? undefined : (key == 'INV' ? "STK_CUS,DMR_REJ" : "PUR_STK,INS_STK,DMR_STK");

        let _this = this;
        this.setState({ tranType, invoiceType: key }, function () {
            _this.fetchDatas({ tranType });
        })

    }
    onFinish = (values: any) => {
        this.fetchDatas(values);
    };

    onFinishFailed = (errorInfo: any) => {
        console.log('Failed:', errorInfo);
    };
    render() {
        const { loading, dataSource, selectedRowKeys, selectedRows, totalCount, pageSize, sumQty, sumCost, visible2, invoiceType } = this.state;
        const columns: ColumnsType<any> = [
            {
                title: '交易日期',
                dataIndex: 'tranDate',
                render: (text: Date) => moment(text).format('YYYY-MM-DD'),
                fixed: 'left',
                width: 110
            },
            {
                title: '物料编码',
                dataIndex: 'partNum',
                fixed: 'left',
                width: 110
            },
            {
                title: '描述',
                dataIndex: 'partDescription',
                ellipsis: true,
                width: 200
            },
            {
                title: '交易数量',
                dataIndex: 'tranQty',
                align: 'right',
                width: 60
            },
            {
                title: '即时库存',
                dataIndex: 'onhandQty',
                width: 110
            },
            {
                title: '单位',
                dataIndex: 'um',
                width: 60
            },
            {
                title: '交易类型',
                dataIndex: 'tranType',
                width: 110
            },
            {
                title: '仓库',
                dataIndex: 'wareHouseCode',
                width: 80
            },
            {
                title: '库位',
                dataIndex: 'binNum',
                width: 80
            },
            {
                title: '批次',
                dataIndex: 'lotNum',
                width: 80
            },
            {
                title: '物料单位成本',
                dataIndex: 'mtlUnitCost',
                align: 'right',
                width: 70
            },
            {
                title: '人工单位成本',
                dataIndex: 'lbrUnitCost',
                align: 'right',
                width: 70
            },
            {
                title: '间接单位成本',
                dataIndex: 'burUnitCost',
                align: 'right',
                width: 70
            },
            {
                title: '外包单位成本',
                dataIndex: 'subUnitCost',
                align: 'right',
                width: 70
            },
            {
                title: '合计',
                dataIndex: 'extCost',
                align: 'right',
                fixed: 'right',
                width: 80
            },
        ];
        const rowSelection = {
            selectedRowKeys,
            onChange: this.onSelectChange,
        };
        return (
            <PageHeaderWrapper>
                <Card>
                    <Space>
                        <Button type="primary"
                            onClick={() => this.fetchDatas()}
                            loading={loading}
                            icon={<SyncOutlined />} >刷新</Button>
                        <Button type="primary" icon={<PlusOutlined />} onClick={() => this.swithDrawer(true)}>高级搜索</Button>
                        <Button type="primary" onClick={() => this.swithModel(true)}>发票输入</Button>
                        <Search style={{ width: 240 }} placeholder="输入关键词搜索" onSearch={value => this.onSearch(value)} />
                    </Space>

                </Card>
                <Card>
                    <Tabs
                        tabBarExtraContent={<Button type="link"><strong>交易量合计：{sumQty} 金额合计：￥{sumCost}</strong></Button>}
                        defaultActiveKey={this.state.tranType} onChange={this.tabChange} type="card">
                        <TabPane tab="交易记录" key="ALL"></TabPane>
                        <TabPane tab="应收账款" key="INV"></TabPane>
                        <TabPane tab="应付账款" key="ONV"></TabPane>
                    </Tabs>
                        <Table
                            rowKey="id"
                            loading={loading}
                            rowSelection={rowSelection}
                            columns={columns}
                            dataSource={dataSource}
                            scroll={{ x: '1800' }}
                            pagination={{
                                onChange: page => {
                                    this.setState({ pageIndex: page }, () => {
                                        this.fetchDatas();
                                    });
                                },
                                pageSize,
                                total: totalCount,
                            }} />
                </Card>
                <Drawer
                    title="高级搜索"
                    width={600}
                    placement="right"
                    closable={false}
                    onClose={() => this.swithDrawer(false)}
                    visible={this.state.visible}
                    destroyOnClose={false}
                >
                    <Form
                        labelCol={{ span: 4 }}
                        wrapperCol={{ span: 18 }}
                        layout="horizontal"
                        onFinish={this.onFinish}
                        onFinishFailed={this.onFinishFailed}
                        ref={this.formRef}
                    >
                        <WhseSelect
                            required={false}
                            showSearch={false}
                            width={200}
                            name='whse'
                            label="仓库"
                        />
                        <Form.Item label="库位" name="binNum" >
                            <Input />
                        </Form.Item>
                        <Form.Item label="物料编码" name="partNum" >
                            <Input />
                        </Form.Item>
                        <Form.Item label="工单号" name="jobNum" >
                            <Input />
                        </Form.Item>
                        <Form.Item label="采购单号" name="poNum" >
                            <Input />
                        </Form.Item>
                        <Form.Item label="订单号" name="orderNum" >
                            <Input />
                        </Form.Item>
                        <VendorSelect
                            required={false}
                            showSearch={true}
                            width={200}
                            name='vendorNum'
                            label="供应商"
                        />
                        <CustSelect
                            required={false}
                            showSearch={true}
                            width={200}
                            name='custNum'
                            label="客户"
                        />
                        <Form.Item label="关键词" name="keywords" >
                            <Input />
                        </Form.Item>
                        <CateSelect
                            layout="交易类型"
                            width={200}
                            name='tranType'
                            label="交易类型"
                        />
                        <Form.Item wrapperCol={{ offset: 4 }}>
                            <Space>
                                <Button type="primary" htmlType="submit">
                                    确定
                                </Button>
                                <Button type="default" onClick={() => this.formRef.current.resetFields()}>
                                    重置条件
                                </Button>
                            </Space>
                        </Form.Item>
                    </Form>
                </Drawer>
                <Modal
                    width={900}
                    title="发票输入"
                    visible={visible2}
                    destroyOnClose={true}
                    onCancel={() => this.swithModel(false)}
                    footer={false}
                >
                    <Invoice data={selectedRows} invoiceType={invoiceType} />
                </Modal>
            </PageHeaderWrapper>
        )
    }
}
export default connect(({ Abp, user }: API.IConnectState) => ({
    response: Abp.response,
    currentUser: user.currentUser,
}))(ViewPage);